package com.atguigu.yygu.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygu.oss.service.FileService;
import com.atguigu.yygu.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        //获取参数
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            //准备文件参数
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            //调用客户端方法上传文件
            String uuid = UUID.randomUUID().toString().replace("-","");
            fileName = uuid + fileName;
            String path = new DateTime().toString("yyyy/MM/dd");
            fileName = path + "/" + fileName;
            ossClient.putObject(bucketName, fileName, inputStream);
            //获取url
            String url = "http://" + bucketName + "." + endpoint + "/" + fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭客户端
            ossClient.shutdown();
        }
    }
}
